<?php
namespace app\admin\controller;
use app\common\model\GoodsBrand;
use think\Validate;
use think\Db;
use think\Session;

class BrandController extends BaseController
{
    public function lists($brand_id=0,$cate_id=0)
    {  
        return view();
    }
    public function getList()
    {
        $where = array_filter(input('post.'));
        if (!empty($where['name'])) {
            $where['name'] = ['like', "%{$where['name']}%"];
        }
        
        $page = max(input('get.page',0),1);
        $page_size = 15;

        $total = Db::name('goods_brand')->where($where)->count();
        $rows = Db::name('goods_brand')->where($where)->page($page, $page_size)->order('add_time desc')->select();

        foreach ($rows as $key => $cate) {
            $rows[$key]['add_time'] = date('Y-m-d H:i',$cate['add_time']);
        }

        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);
    }
    public function getListBySort()
    {
        $sorts = input('post.sort_sel');
        for($i=0; $i<strlen($sorts); $i++) {
            $letters[] = $sorts[$i];
        }
        if (!empty($letters)){
            $where['first_letter'] = ['in',$letters];
        } else {
            $where['first_letter'] = 'A';
        }
        
        $brands = Db::name('goods_brand')->where($where)->order('add_time desc')->select();

        foreach ($brands as $brand) {
            $row = [
                'id'    => $brand['id'],
                'val'   => $brand['name']
            ];
            $rows[] = $row;
        }
        $data = [
            'rows'      => $rows
        ];

        $this->success('成功','',$data);
    }
    public function handle()
    {
        $data = input('post.');
        //数据验证
        $validate = new Validate([
            ['name','require','名称必须'],
            ['first_letter','require|alpha|max:1','首字母必须|首字母必须是字母|首字母只能是1个'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        if (GoodsBrand::where('name',$data['name'])->find()){
            $this->error('品牌已存在');
        }
        $data['add_time'] = time();

        return GoodsBrand::add($data,true);
    }
}